<?php

namespace app\common\api\controller;

use app\common\controller\Log;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\MemberPackages;
use app\common\model\Packages;
use think\Controller;

final class Bonus extends Controller
{
    protected static $bonusRule = [];
    private static $uid = 0;
    private static $user = 0;
    private static $total = 0.00;
    private static $mulriple = 1;

    public function __construct($uid, $total, $mark = 'bill')
    {
        self::$uid = $uid;
        self::$user = Member::find($uid);
        self::$total = $total;
        self::$bonusRule = Db('BonusRule')->find();

        $billMoney = self::$bonusRule['bill_money'];
        if (self::$user->userrank >= 1 && $mark == 'cp') {
            $billMoney = $billMoney * (self::$bonusRule['discount_rate'] * 0.01);
        }

        $mulriple = (int)floor($total / $billMoney);
        self::$mulriple = $mulriple;
    }

    /**
     * 会员激活
     * @param $uid
     * @return bool|int
     */
    private function active($uid)
    {
        $info = Db('member')->field('tuijianid')->find($uid);
        /* 激活用户需要更新字段，激活字段=1;*/
        $data['status'] = 1;
        $data['active_time'] = time();
        //激活用户
        $res1 = Db('member')->where('uid', $uid)->update($data);
        $res2 = Db('ucenter_member')->where('id', $uid)->setField('status', 1);

        if ($res1 && $res2) {
            Db('member')->where('uid', $info['tuijianid'])->setInc('recom_num', 1);
            return true;
        } else {
            return -103;//状态更改失败
        }
    }

    /**
     * 推荐奖
     * @return bool
     */
    public function bonusRecom()
    {
        $tinfo = Db('member')->field('uid,userrank,tuijianid')->where('uid', self::$user['tuijianid'])->where('status', 1)->find();
        if (!$tinfo) {
            return false;
        }

        $recomMoney = self::$bonusRule['recom_money'] * self::$mulriple;
        if ($tinfo['userrank'] <= 1 && self::$mulriple > 1) {
            $recomMoney *= self::$bonusRule['bonus_rate'] * 0.01;
        }
        if ($recomMoney > 0) {
            self::bonusShare($recomMoney, 1, $tinfo['uid'], self::$user);
            self::bonusPing1($tinfo, $recomMoney);
        }
    }

    /**
     * 推荐奖的平级奖
     * @param $buser
     * @param $recomMoney
     * @return bool
     */
    public function bonusPing1($buser, $recomMoney)
    {
        $tinfo = Db('member')->field('uid,userrank')->where('uid', $buser['tuijianid'])->where('status', 1)->find();
        if (!$tinfo) {
            return false;
        }

        $pingMoney = $recomMoney * self::$bonusRule['ping_rate1'] * 0.01;
        if ($pingMoney > 0) {
            self::bonusShare($pingMoney, 2, $tinfo['uid'], $buser);
        }
    }

    /**
     * C区见点奖
     * @return bool
     */
    public function bonusPoint1()
    {
        $pid = self::getCstore();
        if ($pid === false) {
            return false;
        }
        $pointMoney = self::$bonusRule['point_money1'] * self::$mulriple;
        $puserrank = Member::where('uid', $pid)->value('userrank');
        if ($puserrank <= 1 && self::$mulriple > 1) {
            $pointMoney *= self::$bonusRule['bonus_rate'] * 0.01;
        }
        if ($pointMoney > 0) {
            self::bonusShare($pointMoney, 3, $pid, self::$user);
            $this->bonusPointLeader1($pid, $pointMoney);
        }
    }

    /**
     * 检点奖的领导奖
     * @param $pid
     * @param $pointMoney
     */
    public function bonusPointLeader1($pid, $pointMoney)
    {
        $pinfo = Member::where('uid', $pid)->find();
        $tinfo = Member::where('uid', $pinfo->tuijianid)->where('status', 1)->where('level', 2)->find();
        if (!$tinfo) {
            return false;
        }
        $leaderMoney = $pointMoney * self::$bonusRule['point1_leader_rate'] * 0.01;
        if ($leaderMoney > 0) {
            self::bonusShare($leaderMoney, 8, $pinfo->tuijianid, $pinfo);
        }
    }

    /**
     * 店补奖
     * @return bool
     */
    public function bonusStore()
    {
//        $pid = self::getCstore();
//        if ($pid === false) {
//            return false;
//        }
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $where = [
            'status' => 1,
            'userrank' => 2,
            'uid' => ['in', $tuijianids]
        ];
        $tuid = Member::where($where)->order('tdeep desc')->value('uid');
        if (!$tuid) {
            return false;
        }
        $storeMoney = self::$bonusRule['store_money'] * self::$mulriple;
        if ($storeMoney > 0) {
            self::bonusShare($storeMoney, 4, $tuid, self::$user);
            self::bonusLeader($tuid);
        }
    }

    private function getCstore()
    {
        if (self::$user->zone == 3) {
            $pid = Member::where('uid', self::$user['parentid'])->where('status', 1)->value('uid');
            if (!$pid) {
                return false;
            }
        } else {
            $cpinfo = Member::where('uid', 'in', self::$user['parentids'])->where('zone', 3)->order('pdeep', 'desc')->find();
            if (!$cpinfo) {
                return false;
            }

            $pid = Member::where('uid', $cpinfo->parentid)->value('uid');
        }

        return $pid;
    }

    /**
     * 店补奖的领导奖
     * @param $pid
     * @return bool
     */
    private function bonusLeader($tuid)
    {
        $tinfo = Member::find($tuid);
        $ttinfo = Member::where('uid', 'in', $tinfo['tuijianids'])->where('status', 1)->where('userrank', 2)->order('tdeep', 'desc')->find();
        if (!$ttinfo) {
            return false;
        }

        $leaderMoney = self::$bonusRule['store_leader_money'] * self::$mulriple;
        if ($leaderMoney > 0) {
            self::bonusShare($leaderMoney, 5, $ttinfo->uid, $tinfo);
        }
    }

    /**
     * 复购见点奖
     * @return bool
     */
    public function bonusPoint2()
    {
        $pid = self::getCstore();
        if ($pid === false) {
            return false;
        }
        $pointMoney = self::$bonusRule['point_money2'] * self::$mulriple;
        if ($pointMoney > 0) {
            self::bonusShare($pointMoney, 6, $pid, self::$user);
            self::bonusPing2($pid, $pointMoney);
        }
    }

    /**
     * 复购平级奖
     * @param $pid
     * @param $pointMoney
     * @return bool
     */
    public function bonusPing2($pid, $pointMoney)
    {
        $pinfo = Member::find($pid);
        $tinfo = Member::where('uid', 'in', $pinfo['tuijianids'])->where('status', 1)->where('level', 2)->order('tdeep', 'desc')->find();
        if (!$tinfo) {
            return false;
        }

        $pingMoney = self::$bonusRule['ping_rate2'];
        if ($pingMoney > 0) {
            self::bonusShare($pingMoney, 7, $tinfo->uid, $pinfo);
        }
    }

    /**
     * Notes:增加成长值
     * User: Administrator
     * Date: 2023/9/8
     * Time: 8:43
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAchievement()
    {
        if (!self::$user->parentid) {
            return false;
        }

        $pid = self::getCstore();
        if ($pid === false) {
            return false;
        }

//        $map = [
//            'uid' => ['in', trim(self::$uid . ',' . self::$user->parentids, ',')],
//            'status' => ['>=', 1],
//        ];

        Db('member')->where('uid', $pid)->setInc('achievement', self::$total);

        $item = [
            'uid' => $pid,
            'fuid' => self::$uid,
            'money' => self::$total,
            'create_time' => time(),
            'update_time' => time(),
        ];
        Db('achievement_log')->insert($item);

//        $pinfos = Member::where($map)->select();
//        $data = [];
//        foreach ($pinfos as $val) {
//            $item = [
//                'uid' => $val->uid,
//                'fuid' => self::$uid,
//                'money' => self::$total,
//                'create_time' => time(),
//                'update_time' => time(),
//            ];
//
//            $data[] = $item;
//        }

//        Db('achievement_log')->insertAll($data);
    }

    /**
     * 会员级别更新
     */
    public function bonusUpdate()
    {
        if (self::$user->userrank == 0) {
            if (self::$total > self::$bonusRule['bill_money']) {
                $rank = 2;
            } else {
                $rank = 1;
            }
            self::$user->userrank = $rank;
            $rdata = [
                [
                    'uid' => self::$uid,
                    'type' => 1,
                    'updatetype' => 1,
                    'recordtype' => 1,
                    'old' => 0,
                    'new' => $rank,
                    'create_time' => time(),
                    'update_time' => time(),
                ]
            ];

            if (self::$user->level == 0) {
                self::$user->level = 1;
                $rdata[] = [
                    'uid' => self::$uid,
                    'type' => 1,
                    'updatetype' => 2,
                    'recordtype' => 1,
                    'old' => 0,
                    'new' => 1,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
            }

            self::$user->save();

            Db('rank_change_log')->insertAll($rdata);

        } elseif (self::$user->userrank == 1) {
            if (self::$total > self::$bonusRule['bill_money']) {
                $rank = 2;
                self::$user->userrank = $rank;
                self::$user->save();
                $rdata = [
                    'uid' => self::$uid,
                    'type' => 1,
                    'updatetype' => 1,
                    'recordtype' => 1,
                    'old' => 1,
                    'new' => $rank,
                    'create_time' => time(),
                    'update_time' => time(),
                ];

                Db('rank_change_log')->insert($rdata);
            }
        }

        $tinfo = Member::find(self::$user['parentid']);
        if (!$tinfo) {
            return false;
        }

        if ($tinfo->level == 1 && $tinfo->znum >= 2) {
            $tinfo->level = 2;
            $tinfo->save();

            $trdata = [
                'uid' => self::$user['parentid'],
                'type' => 1,
                'updatetype' => 2,
                'recordtype' => 1,
                'old' => 0,
                'new' => 1,
                'create_time' => time(),
                'update_time' => time(),
            ];

            Db('rank_change_log')->insert($trdata);
        }
    }

    /**
     * 奖金生成
     * @param $bonusmoney
     * @param $changetype
     * @param $uid
     * @param $fromuser
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusShare($bonusmoney, $changetype, $uid, $fromuser)
    {
        $map['uid'] = $uid;
        $user = Db('member_finance')->where($map)->find();

        $tax_rate = self::$bonusRule['tax_rate'];
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

        $green_rate = self::$bonusRule['green_rate'];
        if ($green_rate > 100 || $green_rate <= 0) {
            $green = 0;
        } else {
            $green = $green_rate * 0.01;
        }

        $tax_money = $bonusmoney * $tax;
        $green_money = $bonusmoney * $green;
        $actulMoney = $bonusmoney - $tax_money - $green_money;

        $data['hasmoney'] = $user['hasmoney'] + $actulMoney;
        $data['allmoney'] = $user['allmoney'] + $actulMoney;
        if ($green_money) {
            $data['hasgreen'] = $user['hasgreen'] + $green_money;
            $data['allgreen'] = $user['allgreen'] + $green_money;
        }

        $res = Db('member_finance')->where($map)->update($data);

        if ($res) {
            self::bonus('BonusCount', $changetype, $user, $bonusmoney, $actulMoney);
            self::bonus('BonusTotal', $changetype, $user, $bonusmoney, $actulMoney);

            $user = Db('member_finance')->where($map)->find();

            $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 2);
            $money = array('money' => $actulMoney, 'hasmoney' => $user['hasmoney']);
            money_change($type, $uid, $fromuser['uid'], $money);
            unset($type, $money);

            if ($green_money) {
                $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 4);
                $money = array('money' => $green_money, 'hasmoney' => $user['hasgreen']);
                money_change($type, $uid, $fromuser['uid'], $money);
                unset($type, $money);
            }

            finance2($changetype, $bonusmoney); //公司财务统计
        }
    }

    /**
     * @param $table
     * @param $bonustype
     * @param $touser
     * @param $money
     * @param $hasmoney
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function bonus($table, $bonustype, $touser, $money, $hasmoney)
    {
        if ($table == 'BonusCount' || $table == 'bonus_count') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }
        $BCount = Db($table);

        $map['userid'] = $touser['uid'];

        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'userid' => $touser['uid'],
                'usernumber' => $touser['usernumber'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $BCount->insert($data);
        }
    }
}